package com.orhon.smartcampus.modules.teacher.mutation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.GradesDao;
import com.orhon.smartcampus.modules.base.dao.PeriodsDao;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.base.dao.SubjectsDao;
import com.orhon.smartcampus.modules.base.entity.Periods;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.entity.Subjects;
import com.orhon.smartcampus.modules.teacher.dao.TInformationDao;
import com.orhon.smartcampus.modules.teacher.dao.TeacherAndGradesDao;
import com.orhon.smartcampus.modules.teacher.entity.TInformation;
import com.orhon.smartcampus.modules.teacher.entity.TeacherAndGrades;
import com.orhon.smartcampus.modules.teacher.gqlInputModel.GQLTeacherInput;
import com.orhon.smartcampus.modules.teacher.inputMapper.TeacherInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.modules.user.dao.UsersDao;
import com.orhon.smartcampus.modules.user.entity.Users;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddTeacherMutation implements DataFetcher {

    @Autowired
    TInformationDao tInformationDao;

    @Autowired
    UsersDao usersDao;

    @Autowired
    SchoolsDao schoolsDao;

    @Autowired
    TokenService tokenService;

    @Autowired
    GradesDao gradesDao;

    @Autowired
    SubjectsDao subjectsDao;

    @Autowired
    PeriodsDao periodsDao;
    @Autowired
    TeacherAndGradesDao teacherAndGradesDao;

    /**
     * 教师新增/修改接口
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        //String token = (String) SecurityUtils.getSubject().getPrincipal();
        String token = tokenService.getSystemToken();
        //String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX3R5cGUiOiJhZG1pbiIsInNjaG9vbF9pZCI6MSwiZXhwIjoxNTc0NjMzMzUzLCJ1c2VyaWQiOjEsInVzZXJuYW1lIjoidGVhY2hlciJ9.YDTkSQK3DY5QV9yKJwg82I-Byc07ARnHXs5BK9_b-dA";
        Long schoolId = JwtUtils.getSchoolId(token);
        GQLTeacherInput input = TeacherInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        TInformation tInformation = null;

        if (input.getId() != null) {
            tInformation = tInformationDao.get(TInformation.class, input.getId());
            tInformation.setUpdatedAt(new Date());
        } else {
            tInformation = new TInformation();
            tInformation.setCreatedAt(new Date());
        }
        if(input.getUser_id() != null) {
            tInformation.setUserUsersByUserId(usersDao.get(Users.class, input.getUser_id()));
        }
        if(input.getIdcard() != null){

            tInformation.setIdcard(input.getIdcard().toString());
        }
        //性别
        if(input.getGender() != null){

            tInformation.setGender(input.getGender());
        }
        if(input.getBirthday() != null){

            tInformation.setBirthday(input.getBirthday());
        }
        //"籍贯-省";
        if(input.getNative_province_id() != null){

            tInformation.setNativeprovince(input.getNative_province_id());
        }
        //"籍贯-市"
        if(input.getNative_city_id() != null){

            tInformation.setNativecity(input.getNative_city_id());
        }
        //"籍贯-县"
        if(input.getNative_county_id() != null){

            tInformation.setNativecounty(input.getNative_county_id());
        }
        //"出生-省"
        if(input.getBirth_province_id() != null){

            tInformation.setBirthprovince(input.getBirth_province_id());
        }
        //"出生-市"
        if(input.getBirth_city_id() != null){

            tInformation.setBirthcity(input.getBirth_city_id());
        }
        //"出生-县"
        if(input.getBirth_county_id() != null){

            tInformation.setBirthcounty(input.getBirth_county_id());
        }
        //人才类型
        if(input.getType() != null){

            tInformation.setType(input.getType());
        }
        if(input.getEmail() != null){

            tInformation.setEmail(input.getEmail());
        }
        if(input.getTelnumber() != null){

            tInformation.setTelnumber(input.getTelnumber());
        }
        if(input.getNationality() != null){

            tInformation.setNationality(input.getNationality());
        }
        if(input.getPolitical_type() != null){

            tInformation.setPoliticaltype(input.getPolitical_type());
        }
        if(input.getWork_status() != null){

            tInformation.setWorkstatus(input.getWork_status());
        }
        if(input.getWork_date() != null){

            tInformation.setWorkdate(input.getWork_date());
        }
        if(input.getJob_title() != null){

            tInformation.setJobtitle(input.getJob_title());
        }
        if(input.getEducation() != null){

            tInformation.setEducation(input.getEducation());
        }
        if(input.getDegree() != null){

            tInformation.setDegree(input.getDegree());
        }
        if(input.getMaster_supervisor() != null){

            tInformation.setMastersupervisor(input.getMaster_supervisor());
        }
        if(input.getTeach() != null){

            tInformation.setTeach(input.getTeach());
        }
        if(input.getTalent_category_six() != null){

            tInformation.setTalentcategorySix(JSON.toJSONString(input.getTalent_category_six()));
        }
        if(input.getTalent_category_nine() != null){

            tInformation.setTalentcategoryNine(JSON.toJSONString(input.getTalent_category_nine()));
        }
        //"现住址-省"
        if(input.getCmbprovince3_id() != null){

            tInformation.setCmbprovince3(input.getCmbprovince3_id());
        }
        //"现住址-市"
        if(input.getCmbcity3_id() != null){

            tInformation.setCmbcity3(input.getCmbcity3_id());
        }
        //"现住址-县"
        if(input.getCmbcounty3_id() != null){

            tInformation.setCmbcounty3(input.getCmbcounty3_id());
        }
        //"户籍所在地-省"
        if(input.getCmbprovince2_id() != null){

            tInformation.setCmbprovince2(input.getCmbprovince2_id());
        }
        //"户籍所在地-市"
        if(input.getCmbcity2_id() != null){

            tInformation.setCmbcity2(input.getCmbcity2_id());
        }
        //"户籍所在地-县"
        if(input.getCmbcounty2_id() != null){

            tInformation.setCmbcounty2(input.getCmbcounty2_id());
        }
        //"学校"
        if(schoolId != null) {
            tInformation.setBaseSchoolsBySchoolId(schoolsDao.get(Schools.class, schoolId));
        }
        //"民族"
        if(input.getNation() != null){

            tInformation.setNation(input.getNation());
        }

        //"公安身份证备案照片"
        if(input.getImgphotos() != null){

            tInformation.setImgphotos(input.getImgphotos());
        }
        //"本人签字图片"
        if(input.getSignimg() != null){

            tInformation.setSignimg(input.getSignimg());
        }
        //"教师姓名"
        if(input.getName() != null){

            tInformation.setTeacherName(JSON.toJSONString(input.getName()));
        }
        //"简介"
        if(input.getIntroduction() != null){

            tInformation.setIntroduction(JSON.toJSONString(input.getIntroduction()));
        }
        //"年级"
        /* if(input.getGrades() != null){
           List<Grades> ttt=new ArrayList<>();
            input.getGrades().forEach(g -> {
                try {
                    Grades a = gradesDao.findById(Long.valueOf(g));
                    ttt.add(a);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            tInformation.setGrades(ttt);
        }*/

        //"学科"
        if(input.getSubjects() != null){
            List<Subjects> ttt=new ArrayList<>();
            input.getSubjects().forEach(g -> {
                try {
                    Subjects a = subjectsDao.findById(Long.valueOf(g));
                    ttt.add(a);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            tInformation.setSubjects(ttt);
        }
        //学段
        if(input.getPeriods() != null){
            List<Periods> ttt=new ArrayList<>();
            input.getPeriods().forEach(g -> {
                try {
                    Periods a = periodsDao.findById(Long.valueOf(g));
                    ttt.add(a);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            tInformation.setPeriods(ttt);
        }
        try{
            Long userId;
            /**
             * 是否存在基础用户信息
             */
            DetachedCriteria u_criteria = DetachedCriteria.forClass(Users.class);
            u_criteria.add(Restrictions.isNull("deleted_at"));
            u_criteria.add(Restrictions.eq("idCard", input.getIdcard()));
            List<Users> users = (List<Users>) usersDao.findByCriteria(u_criteria);
            Users old_user = users.size()>0?users.get(0):null;
            if (old_user != null) {
                userId = old_user.getId();
            } else {
                Users user = new Users();
                if(input.getIdcard() != null){

                    user.setIdCard(input.getIdcard());
                }
                if (input.getTelnumber()!=null){
                    user.setMobile(input.getTelnumber());
                }
                if (input.getName().getZh() != null){
                    user.setUsername(input.getName().getZh());
                }
                BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                String encode = bCryptPasswordEncoder.encode("123456");
                //String s = convertJavaBcryptPassword(encode);
                user.setPassword(encode);
                if(input.getEmail() != null){

                    user.setEmail(input.getEmail());
                }
                user.setUser_type("teacher");
                Schools schools = schoolsDao.get(Schools.class , schoolId);
                user.setSchool(schools);
                Users new_user;
                try {
                    new_user = usersDao.save(user);
                } catch (Exception e) {
                    return Result.error(500, "" + e);
                }
                userId = new_user.getId();
            }
            tInformation.setUserUsersByUserId(usersDao.get(Users.class, userId));
            tInformationDao.saveOrUpdate(tInformation);
            if(tInformation.getId().longValue()!=0){
                if(input.getGrades() != null){
                    List<Integer> gradesIds = input.getGrades();//年级
                    List<TeacherAndGrades> periodCount = teacherAndGradesDao.GradesList(tInformation.getId().longValue());//是否有老师记录
                    for (TeacherAndGrades grades : periodCount) {
                       // teacherAndGradesDao.update(grades);//假删
                        teacherAndGradesDao.deleteById(grades.getId());
                    }
                    //if(periodCount>0){
                    for(Integer gid:gradesIds){
                        Long pid = gid.longValue();
                        TeacherAndGrades teacherAndGrades=new TeacherAndGrades(tInformation.getId(),pid);
                        teacherAndGradesDao.saveOrUpdate(teacherAndGrades);//新数据
                    }

                }

                //session.save(teacherAndPeriods);
                //transaction.commit();

            }
        }
        catch (Exception e){
            return Result.error(500,""+e);
        }
        return Result.ok();
    }

    private String convertJavaBcryptPassword(String oldPass) {
        String old_password = oldPass;
        String new_password = "";
        if (old_password.charAt(2) == 'a') {
            StringBuilder strBuilder = new StringBuilder(old_password);
            strBuilder.setCharAt(2, 'y');
            new_password = strBuilder.toString();
            return new_password;
        } else {
            return old_password;
        }
    }

}

